package com.crazypos.security;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.crazypos.common.utils.RedisUtil;
import com.crazypos.common.utils.SecurityUtil;
import com.crazypos.constant.CommonConstant;
import com.crazypos.dao.PermissionDao;
import com.crazypos.pojo.PermissionEntity;
import com.crazypos.security.entity.UserDetailEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/***
 * 自定义权限校验注解
 */
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        // 获取用户信息
        UserDetailEntity userDetail = (UserDetailEntity) authentication.getPrincipal();

        // 获取用户角色ROLE ID
        String userRoleId = userDetail.getRoleId();

        // 获取用户的机构ID
        String userOrganizationId = userDetail.getOrganizationId();

        // 获取 redis key
        String RoleKey = SecurityUtil.createPermissionKey(userOrganizationId, userRoleId);

        String permissionListStr = redisUtil.hget(RoleKey, CommonConstant.PERMISSION_FIELDS_NAME);


        if (StringUtils.isEmpty(permissionListStr)) {
            // 缓存不存在，查询数据库并存入缓存
            List<PermissionEntity> permissionEntities = permissionDao.getPermissionsByRoleId(userRoleId);
            List<String> permissionList = new ArrayList<>();
            for (PermissionEntity permissionEntity :
                    permissionEntities) {
                permissionList.add(permissionEntity.getValue());
            }
            redisUtil.hset(RoleKey, CommonConstant.PERMISSION_FIELDS_NAME, JSON.toJSONString(permissionList));
            if (permissionList.contains(permission)) {
                return true;
            }
        } else {
            List<String> permissions = JSON.parseObject(permissionListStr, ArrayList.class);
            if (permissions.contains(permission)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
